package com.example.nirvana.dataStructure;

/**
 * 队列
 */
public class MyQueue {
    private final int SIZE;
    // 用于存放队列数据的数组
    private int[] queue;
    // 队头和队尾的标识
    private int head;
    private int end;

    public MyQueue(int size) {
        SIZE = size;
        queue = new int[SIZE];
        head = 0;
        end = 0;
    }

    /**
     * 获取head&end移动后的位置
     *
     * @param i
     * @return
     */
    private int next(int i) {
        return (i+1)%SIZE;
    }

    /**
     * 判断队列是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return end == head;
    }

    /**
     * 判断队列是否为满队
     *
     * @return
     */
    public boolean isFull() {
        return next(end) == head; // 当next(end)==head时,此时队列为满,否则队列不满
    }

    /**
     * 入队
     *
     * @param data
     * @throws Exception
     */
    public void offer(int data) throws Exception {
        if(isFull()) {
            throw new Exception("queue is full");
        }else {
            queue[end] = data;
            end = next(end);
        }
    }

    /**
     * 出队
     *
     * @return
     * @throws Exception
     */
    public int poll() throws Exception {
        if(isEmpty()) {
            throw new Exception("queue is empty");
        }else {
            int result = queue[head];
            head = next(head);
            return result;
        }
    }





}
